/**
 * 用户模型
 * @module models/user
 */

const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcrypt');
const config = require('../config/config');

/**
 * 用户类，提供用户相关的数据库操作
 */
class User {
  /**
   * 创建新用户
   * @param {Object} userData - 用户数据
   * @param {string} userData.username - 用户名
   * @param {string} userData.email - 邮箱
   * @param {string} userData.password - 密码
   * @returns {Promise<Object>} 创建的用户对象
   */
  static async create(userData) {
    const { username, email, password } = userData;
    
    // 哈希密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    
    return new Promise((resolve, reject) => {
      const db = new sqlite3.Database(config.dbPath);
      
      // 检查用户名是否已存在
      db.get('SELECT id FROM users WHERE username = ?', [username], (err, row) => {
        if (err) {
          db.close();
          return reject(err);
        }
        
        if (row) {
          db.close();
          return reject(new Error('用户名已存在'));
        }
        
        // 检查邮箱是否已存在
        db.get('SELECT id FROM users WHERE email = ?', [email], (err, row) => {
          if (err) {
            db.close();
            return reject(err);
          }
          
          if (row) {
            db.close();
            return reject(new Error('邮箱已被使用'));
          }
          
          // 创建新用户
          const registerDate = new Date().toISOString();
          db.run(
            'INSERT INTO users (username, email, password, is_pro, is_admin, register_date) VALUES (?, ?, ?, ?, ?, ?)',
            [username, email, hashedPassword, 0, 0, registerDate],
            function(err) {
              if (err) {
                db.close();
                return reject(err);
              }
              
              // 获取新创建的用户
              db.get('SELECT id, username, email, is_admin, register_date FROM users WHERE id = ?', [this.lastID], (err, user) => {
                db.close();
                if (err) {
                  return reject(err);
                }
                
                // 转换字段名称
                if (user.register_date) {
                  user.registerDate = user.register_date;
                  delete user.register_date;
                }
                
                if (user.is_admin !== undefined) {
                  user.isAdmin = user.is_admin === 1;
                  delete user.is_admin;
                }
                
                resolve(user);
              });
            }
          );
        });
      });
    });
  }
  
  /**
   * 根据ID查找用户
   * @param {number} id - 用户ID
   * @returns {Promise<Object>} 用户对象
   */
  static async findById(id) {
    return new Promise((resolve, reject) => {
      const db = new sqlite3.Database(config.dbPath);
      
      db.get(
        `SELECT 
          id, username, email, is_pro, is_admin, pro_expiry_date, register_date, last_login 
        FROM users WHERE id = ?`, 
        [id], 
        (err, user) => {
          db.close();
          if (err) {
            return reject(err);
          }
          
          if (!user) {
            return resolve(null);
          }
          
          // 转换布尔值
          user.isPro = user.is_pro === 1;
          delete user.is_pro;
          
          user.isAdmin = user.is_admin === 1;
          delete user.is_admin;
          
          // 转换日期格式
          if (user.pro_expiry_date) {
            user.proExpiryDate = user.pro_expiry_date;
          }
          delete user.pro_expiry_date;
          
          if (user.register_date) {
            user.registerDate = user.register_date;
          }
          delete user.register_date;
          
          if (user.last_login) {
            user.lastLogin = user.last_login;
          }
          delete user.last_login;
          
          resolve(user);
        }
      );
    });
  }
  
  /**
   * 通过用户名查找用户
   * @param {string} username - 用户名
   * @returns {Promise<Object>} 用户对象，包含密码
   */
  static async findByUsername(username) {
    return new Promise((resolve, reject) => {
      const db = new sqlite3.Database(config.dbPath);
      
      db.get(
        'SELECT * FROM users WHERE username = ?', 
        [username], 
        (err, user) => {
          db.close();
          if (err) {
            return reject(err);
          }
          
          if (!user) {
            return resolve(null);
          }
          
          // 转换布尔值
          user.isPro = user.is_pro === 1;
          delete user.is_pro;
          
          user.isAdmin = user.is_admin === 1;
          delete user.is_admin;
          
          // 转换日期格式
          if (user.pro_expiry_date) {
            user.proExpiryDate = user.pro_expiry_date;
          }
          delete user.pro_expiry_date;
          
          if (user.register_date) {
            user.registerDate = user.register_date;
          }
          delete user.register_date;
          
          if (user.last_login) {
            user.lastLogin = user.last_login;
          }
          delete user.last_login;
          
          resolve(user);
        }
      );
    });
  }
  
  /**
   * 更新用户信息
   * @param {number} id - 用户ID
   * @param {Object} userData - 要更新的用户数据
   * @returns {Promise<Object>} 更新后的用户对象
   */
  static async update(id, userData) {
    return new Promise((resolve, reject) => {
      const db = new sqlite3.Database(config.dbPath);
      
      // 构建更新字段和参数
      const updateFields = [];
      const values = [];
      
      if (userData.email) {
        updateFields.push('email = ?');
        values.push(userData.email);
      }
      
      if (userData.password) {
        updateFields.push('password = ?');
        values.push(userData.password);
      }
      
      if (userData.isPro !== undefined) {
        updateFields.push('is_pro = ?');
        values.push(userData.isPro ? 1 : 0);
      }
      
      if (userData.isAdmin !== undefined) {
        updateFields.push('is_admin = ?');
        values.push(userData.isAdmin ? 1 : 0);
      }
      
      if (userData.proExpiryDate) {
        updateFields.push('pro_expiry_date = ?');
        values.push(userData.proExpiryDate);
      }
      
      if (userData.lastLogin) {
        updateFields.push('last_login = ?');
        values.push(userData.lastLogin);
      }
      
      // 没有要更新的字段
      if (updateFields.length === 0) {
        db.close();
        return resolve(null);
      }
      
      // 添加ID参数
      values.push(id);
      
      const updateQuery = `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`;
      
      db.run(updateQuery, values, function(err) {
        if (err) {
          db.close();
          return reject(err);
        }
        
        if (this.changes === 0) {
          db.close();
          return resolve(null);
        }
        
        // 获取更新后的用户信息
        db.get(
          `SELECT 
            id, username, email, is_pro, is_admin, pro_expiry_date, register_date, last_login 
          FROM users WHERE id = ?`, 
          [id], 
          (err, user) => {
            db.close();
            
            if (err) {
              return reject(err);
            }
            
            if (!user) {
              return resolve(null);
            }
            
            // 转换布尔值
            user.isPro = user.is_pro === 1;
            delete user.is_pro;
            
            user.isAdmin = user.is_admin === 1;
            delete user.is_admin;
            
            // 转换日期格式
            if (user.pro_expiry_date) {
              user.proExpiryDate = user.pro_expiry_date;
            }
            delete user.pro_expiry_date;
            
            if (user.register_date) {
              user.registerDate = user.register_date;
            }
            delete user.register_date;
            
            if (user.last_login) {
              user.lastLogin = user.last_login;
            }
            delete user.last_login;
            
            resolve(user);
          }
        );
      });
    });
  }
}

module.exports = User; 